package com.hzya.frame.utils.help;

import freemarker.core.CollectionAndSequence;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.MapModel;
import freemarker.ext.util.ModelFactory;
import freemarker.template.*;

import java.util.Map;
import java.util.Set;

/**
 * @description:
 * @author: gjh
 * @Date Created in ${Data} 14:34
 */
public class SevenStarBeanWrapper extends BeansWrapper {
    private static final boolean altMapWrapper = true;

    public SevenStarBeanWrapper() {
    }

    public TemplateModel wrap(Object object) throws TemplateModelException {
        if (object instanceof TemplateBooleanModel) {
            return super.wrap(object);
        } else {
            return object instanceof Map ? this.getInstance(object, FriendlyMapModel.FACTORY) : super.wrap(object);
        }
    }

    private static final class FriendlyMapModel extends MapModel implements TemplateHashModelEx {
        static final ModelFactory FACTORY = new ModelFactory() {
            public TemplateModel create(Object object, ObjectWrapper wrapper) {
                return new FriendlyMapModel((Map)object, (BeansWrapper)wrapper);
            }
        };

        public FriendlyMapModel(Map map, BeansWrapper wrapper) {
            super(map, wrapper);
        }

        public boolean isEmpty() {
            return ((Map)this.object).isEmpty();
        }

        protected Set keySet() {
            return ((Map)this.object).keySet();
        }

        public TemplateCollectionModel values() {
            return new CollectionAndSequence(new SimpleSequence(((Map)this.object).values(), this.wrapper));
        }
    }
}
